<template>
  <div id="app">
    <!-- 主体部分 -->
    <el-row type="flex" justify="space-around">
      <!-- 侧边楼层导航 -->
      <el-col class="hidden-sm-and-down" :sm="1" :md="2">
        <div class="sidebar">
          <div class="nav" v-for="(item, index) in siteList" :key="item.ftitle" @click="setFloorNavMountClick(index)">{{ item.ftitle }}</div>
        </div>
      </el-col>
      <!-- 站点主体部分 -->
      <el-col :xs="22" :sm="22" :md="20">
        <el-row type="flex" justify="space-around" style="margin-top: 32px;position: sticky;top: 0;z-index: 100;">
          <el-col class="hidden-sm-and-down" :sm="24" :md="12">
            <el-input ref="searchInput" placeholder="请输入搜索内容" v-model="formSearch.searchKey" clearable>
              <el-button slot="prepend" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
        </el-row>
        <siteList :siteList="siteList" :typeList="typeList" :code="code" @refresh="getSiteList"></siteList>
      </el-col>
      <!-- 联系我 -->
      <el-col class="hidden-md-and-down" :md="1">
        <div class="contact">
          <transition name="el-fade-in-linear">
            <div class="item" id="to-top" v-show="showBackTop" @click="toTop()">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-huojian" />
              </svg>
            </div>
          </transition>
          <div class="contact-item">
            <!-- <div class="item" id="qq" @click="goToQQ()" @mouseover="icon.qq = '#icon-qq-color'" @mouseout="icon.qq = '#icon-qq'">
              <svg class="icon" aria-hidden="true">
                <use :xlink:href="icon.qq" />
              </svg>
            </div> -->
            <!-- <div
              id="weixin"
              class="item weixin-btn"
              @mouseover="
                showWeixin = true
                icon.weixin = '#icon-weixin-color'
              "
              @mouseout="
                showWeixin = false
                icon.weixin = '#icon-weixin'
              "
            >
              <svg class="icon" aria-hidden="true">
                <use :xlink:href="icon.weixin" />
              </svg>
              <div>
                <transition name="el-zoom-in-center">
                  <img src="https://qiniuyun.zhichi921.com/weixin1.jpg" alt v-show="showWeixin" />
                </transition>
              </div>
            </div> -->
            <div class="item" id="" @click="$message('右键点我')" @contextmenu.prevent="onContextmenu">工具</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- <div style="height:1000px"></div> -->


    <!-- 底部 -->
    <div class="footer">
      <div class="footer-inner">
        <el-input placeholder="权限密钥" v-model="code" @change="codeChange" style="width:300px">
            <template slot="prepend">密钥</template>
        </el-input>
      </div>
    </div>

    <!-- 新增类型 -->
    <el-dialog title="新增分类" :visible.sync="typeDialog">
      <el-form :model="typeForm" :rules="typeRules" ref="typeFormRef">
        <el-form-item label="分类名称" prop="type">
          <el-input type="textarea" :rows="4" placeholder="请输入类型名称" v-model="typeForm.type"></el-input>
        </el-form-item>
        <el-form-item class="form-footer">
          <el-button size="medium" @click="typeDialog = false">取 消</el-button>
          <el-button size="medium" type="primary" @click="addType">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增链接 -->
    <el-dialog title="新增网址" :visible.sync="linkDialog" :close-on-click-modal="false">
      <el-form :model="linkForm" :rules="linkRules" ref="linkFormRef" label-position="left"  label-width="90px">
        <el-form-item label="网址URL" prop="url">
          <el-input type="input" placeholder="请输入网址URL" v-model="linkForm.url"></el-input>
        </el-form-item>
        <el-form-item label="网址标题" prop="title">
          <el-input type="input" :rows="4" placeholder="请输入网址标题" v-model="linkForm.title"></el-input>
        </el-form-item>
        <el-form-item label="网址简介" prop="desc">
          <el-input type="input" :rows="4" placeholder="请输入网址简介" v-model="linkForm.desc"></el-input>
        </el-form-item>
        <el-form-item label="网址分类" prop="type">
          <el-select v-model="linkForm.type" placeholder="请选分类">
            <el-option :label="item.type" :value="item.type" v-for="item in typeList" :key="item._id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="网址图标">
          <el-input type="input" :rows="4" placeholder="请输入网站图标地址" v-model="linkForm.icon"></el-input>
        </el-form-item>
        <el-form-item class="form-footer">
          <el-button size="medium" @click="linkDialog = false">取 消</el-button>
          <el-button size="medium" type="primary" @click="addLink">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
import SiteList from '@/components/SiteList'
import { getSiteList, addType, getTypeList, addLink } from '@/api'
import utils from '@/utils/index.js'
export default {
  name: 'app',
  data() {
    return {
      code:'',
      keyword: '',
      siteList: [],
      linkData:[],
      element: {
        nav_item: null,
        floor_item: null,
      },
      showBackTop: false,
      showWeixin: false,
      rules: {
        content: [{ required: true, message: '请填写反馈内容', trigger: 'blur' }],
      },
      timer: null,
      icon: {
        qq: '#icon-qq',
        weixin: '#icon-weixin',
      },
      loading: null,
      searchTimer: null, 
      qq: '1843544121',
      typeDialog:false,
      typeForm:{
        type: '',
        code: '',
      },
      typeRules: {
        type: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
      },
      typeList:[],
      linkDialog:false,
      defaultLinkForm:{
        url: '',
        title: '',
        desc: '',
        type: '',
        icon: '',
        clicks: 1,
        code: '',
      },
      linkForm:{
        url: '',
        title: '',
        desc: '',
        type: '',
        icon: '',
        clicks: 1,
        code: '',
      },
      linkRules: {
        url: [{ required: true, message: '请输入网址', trigger: 'blur' }],
        title: [{ required: true, message: '请输入网址标题', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入网址简介', trigger: 'blur' }],
        type: [{ required: true, message: '请选择网址类别', trigger: 'blur' }],
        
      },
      linkList:[],
      formSearch: {
				searchKey: '',
				timer: null
			},
    }
  },
  components: {
    SiteList,
    // Cute,
  },
  created() {
    this.code = localStorage.getItem('code');
    this.loading = this.$loading({ fullscreen: true })
    this.getSiteList()
    this.getTypeList();
    
  },
  methods: {
    onContextmenu(event) {
      this.$contextmenu({
        items: [
          {
            label: "新增网址",
            onClick: () => {
              this.linkDialog = true;
            }
          },
          { label: "重新加载", divided: true, icon: "el-icon-refresh",
            onClick: () => {
              location.reload();
            }
          },
          {
            label: "新增类别",
            divided: true,
            onClick: () => {
              this.typeDialog = true;
              // this.$message("新增类别");
            }
          },
          {
            label: "注册账号",
            onClick: () => {
              // this.typeDialog = true;
              this.$message("觉得没必要，还没写！");
            }
          },
        ],
        event,
        //x: event.clientX,
        //y: event.clientY,
        customClass: "custom-class",
        zIndex: 3,
        minWidth: 230
      });
      return false;
    },
    addType(){
      let that = this;
      this.$refs['typeFormRef'].validate((valid) => {
        if (valid) {
          let hasType = this.typeList.some(function(item){
            // console.log('item',item);
            return item.type == that.typeForm.type
          });
          console.log('hasType',hasType);
          if (hasType){this.$message.error('已经有了');return false};
          this.typeForm.code = this.code;
          addType(this.typeForm).then(res => {
            this.$message.success(res.msg);
            this.typeDialog = false;
            this.typeForm.type = '';
            this.getTypeList();
          }).catch(err => {
            console.log('addType err',err);
          })
        } else {
          this.$message('请填写完整');
          return false;
        }
      });
      
    },
    addLink(){
      let that = this;
      this.linkForm.code = this.code;
      this.$refs['linkFormRef'].validate((valid) => {
        if (valid) {
          addLink(this.linkForm).then(res => {
            this.$message.success(res.msg);
            this.linkDialog = false;
            this.linkForm = this.defaultLinkForm;
            this.getSiteList();
          }).catch(err => {
            console.log('addType err',err);
          })
        } else {
          this.$message('请填写完整');
          return false;
        }
      });
      
    },
    async getTypeList() {
      console.log('this.code',this.code);
      const res = await getTypeList({code:this.code})
      this.typeList = res.data;
    },
    async getSiteList() {
      const res = await getSiteList({code:this.code})
      // console.log('getSiteList',res)
      let siteArr = res.data;

    
     this.siteList = this.groupArr(siteArr);
      this.linkData = res.data;
      console.log('this.siteList',this.siteList)
      this.sitetotalnum = res.totalCount
    },
    groupArr(arr) {
      var map = {},
        result = [];
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.type]) {
          result.push({
            ftitle: ai.type,
            list: [ai]
          });
          map[ai.type] = ai;
        } else {
          for (var j = 0; j < result.length; j++) {
            var dj = result[j];
            if (dj.ftitle == ai.type) {
              dj.list.push(ai);
              break;
            }
          }
        }
      }
      return result;
    },
    codeChange(e){
      localStorage.setItem('code',e);
    },
    goToQQ() {
      window.open('http://wpa.qq.com/msgrd?v=3&uin=' + this.qq + '&site=qq&menu=yes', '_blank')
    },
    /**
     * 监听窗口滚动楼层导航动态定位
     */
    floorSrcollEventListener() {
      const { nav_item, floor_item } = this.element
      const window_scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      for (let i = 0, len = floor_item.length; i < len; i++) {
        let floor_offsetTop = floor_item[i].offsetTop - floor_item[0].offsetTop
        if (window_scrollTop >= floor_offsetTop) {
          for (let n = 0, len = nav_item.length; n < len; n++) {
            const current_classList = nav_item[n].classList
            i === n ? current_classList.add('active') : current_classList.remove('active')
          }
        }
      }
    },
    /**
     * 设置楼层导航事件驱动方法
     * @param {Number} index  楼层下标
     */
    setFloorNavMountClick(index) {
      const { floor_item } = this.element
      let floor_offsetTop = floor_item[index].offsetTop - floor_item[0].offsetTop,
        window_scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
        timer = {
          step: 60,
          times: 16,
          FLOOR_OFFSETTOP: floor_offsetTop,
        }
        //尝试修复bug
        // let availHeight = window.screen.availHeight;
        // let scrollHeight = document.body.scrollHeight;
        // let ah = scrollHeight - availHeight;
        // if(floor_offsetTop>ah){floor_offsetTop=ah}
        // console.log('floor_offsetTop',floor_offsetTop);
        //  console.log('window_scrollTop',window_scrollTop);
        // console.log(' document.body.scrollHeight', document.body.scrollHeight);
        // console.log(' window.screen.availHeight',  window.screen.availHeight);
         //尝试修复bug

      if (window_scrollTop > floor_offsetTop) {
        this.setFloorScrollArrowUp(timer)
      } else if (window_scrollTop == floor_offsetTop) {
        return false
      } else {
        this.setFloorScrollArrowDown(timer)
      }
    },
    /**
     * 设置楼层向上滚动
     * @param {Object} timer 定时器配置
     */
    setFloorScrollArrowUp(timer) {
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        let window_scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        if (window_scrollTop <= timer.FLOOR_OFFSETTOP) {
          document.documentElement.scrollTop = timer.FLOOR_OFFSETTOP
          document.body.scrollTop = timer.FLOOR_OFFSETTOP
          clearInterval(this.timer)
        } else {
          document.documentElement.scrollTop = window_scrollTop - timer.step
          document.body.scrollTop = window_scrollTop - timer.step
        }
      }, timer.times)
    },
    /**
     * 设置楼层向下滚动
     * @param {Object} timer 定时器配置
     */
    setFloorScrollArrowDown(timer) {
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        let window_scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        if (window_scrollTop >= timer.FLOOR_OFFSETTOP) {
          document.documentElement.scrollTop = timer.FLOOR_OFFSETTOP
          document.body.scrollTop = timer.FLOOR_OFFSETTOP
          clearInterval(this.timer)
        } else {
          document.documentElement.scrollTop = window_scrollTop + timer.step
          document.body.scrollTop = window_scrollTop - timer.step
        }
      }, timer.times)
    },
    // 显示返回顶部按钮
    handleScroll() {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      if (scrollTop >= 120) {
        this.showBackTop = true
      } else if (scrollTop < 120) {
        this.showBackTop = false
      }
    },
    // 返回顶部
    toTop() {
      let top = document.documentElement.scrollTop || document.body.scrollTop
      // 实现滚动效果
      const timeTop = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= 80
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
    },
    search(){
      let that = this;
      this.siteList = [
        {
          ftitle:'搜索结果',
          list:[]
        }
      ];
      this.linkData.map((link)=>{
          if(link.title.indexOf(this.formSearch.searchKey)!=-1    || link.desc.indexOf(this.formSearch.searchKey)!=-1 || link.url.indexOf(this.formSearch.searchKey)!=-1){
              that.siteList[0].list.push(link);
          }
      })
    },
    searchKey(e) {     
      var key = window.event.keyCode ? window.event.keyCode : window.event.which;
      if (key === 70 && e.ctrlKey) {
        this.$refs['searchInput'].focus()
        e.preventDefault()
      }
    }
  },
  watch: {
    'formSearch.searchKey': {
      handler(value) {
        console.log('value',value);
        if(!value) {
          this.siteList = this.groupArr(this.linkData);
          return;
        };
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.search();
          this.toTop();
        }, 500)
      },
      deep: true
    }
    
  },
  mounted() {
    // 获取楼层及导航元素
    setTimeout(() => {
      this.element = {
        nav_item: document.getElementsByClassName('nav'),
        floor_item: document.getElementsByClassName('floor-item'),
      }
      this.element.nav_item[0].classList.add('active')
      window.addEventListener('scroll', this.floorSrcollEventListener)
    }, 200)
    // 添加监听屏幕滚动事件
    window.addEventListener('scroll', this.handleScroll)
    this.loading.close()
    document.addEventListener('keydown', this.searchKey)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.floorSrcollEventListener)
  },
}
</script>

<style scoped lang="scss">
.sidebar {
  position: sticky;
  top: 32px;
  left: 1.5%;
  margin-top: 32px;
  height: 480px;
  border-radius: 10px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  text-align: center;
  padding: 10px 0;
  color: #444;
  .nav {
    cursor: pointer;
    font-size: 15px;
  }
}
.active {
  color: #ff5a00;
}
.contact {
  position: sticky;
  top: 680px;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 192px;
  .item {
    width: 46px;
    height: 40px;
    background-color: #e1e9ee;
    margin-top: 8px;
    line-height: 40px;
    text-align: center;
    color: #ffffff;
    font-size: 13px;
    border-radius: 4px;
    transition: 0.3s;
    cursor: pointer;
    &:hover {
      color: #ffa617;
    }
    .icon {
      font-size: 20px;
    }
  }
  .contact-item {
    position: absolute;
    bottom: 0;
  }
  #fankui {
    background-color: #99aebc;
    &:hover {
      color: #222222;
    }
  }
  #to-top {
    display: flex;
    align-items: center;
    justify-content: center;
    .icon {
      width: 24px;
      height: 24px;
    }
  }
}
.weixin-btn {
  position: relative;
  & > div {
    position: absolute;
    left: -190px;
    top: -150px;
    img {
      width: 160px;
      height: 284px;
      border-radius: 10px;
    }
  }
}
.form-footer {
  display: flex;
  flex-direction: row-reverse;
  margin-top: 20px;
}
.footer {
  text-align: center;
  height:60px;
  .footer-inner{
    position:fixed;
    left:0;
    right:0;
    bottom:0;
    background-color: #e5e5e5;
  }

}
::v-deep .el-textarea__inner {
  font-family: 'Pingfang-Medium';
}
</style>
